let app = getApp()
let count = 0
//微信请求封装
let debounce = (func) => {
  let timer = null
  return (args) => {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func.call(this,args)
    }, 2000)
  }
}

let show = debounce( wx.showModal)

function fetchApi(url, params) {

  return new Promise((resolve, reject) => {
    // wx.showLoading({
    //   title: '加载中',
    // })
    wx.request({
      url: app.globalData.host + url,
      data: params,
      method: 'POST',
      success: (res) => {
        if (res.data.code == 2000) {
          //showToast(res.data.msg)
          app.globalData.err = ''
          resolve(res.data.data)
        } else if (res.data.code == 5001 || res.data.code == 5000) {
          app.globalData.err = 1;
          // console.log(app.globalData.err)
          if(app.globalData.isProfile) return;
          show({
            title: '提示',
            content: '您登录状态已过期，无法继续浏览，是否重新登录',
            success: (res1) => {
              if (res1.confirm) {
                wx.switchTab({
                  url: "/pages/personal/personal",
                })
              }
            }
          })
        } else {

          // showToast(res.data.msg + '', 'http://qnwmfx.laigl.com/iconimg/warn.png')
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }


        // wx.hideLoading()
      },
      fail: reject
    })
  })
};

//微信showToast封装
function showToast(title, image, ms = 1500) {
  return new Promise((resolve, reject) => {
    wx.showToast({
      title: title,
      duration: ms,
      image: image,
      success: resolve,
      fail: reject
    })
  })
};






module.exports = {
  fetchApi,
  showToast,
}